<template>
  <div class="dashboard-container">
    <!-- 顶部统计数据卡片 -->
    <div class="stat-cards-wrapper">
      <div
        class="stat-cards"
        ref="statCardsRef"
        @mouseenter="handleMouseEnter"
        @mouseleave="handleMouseLeave"
      >
        <stat-card
          v-for="item in statCards"
          :key="item.id"
          :title="item.title"
          :value="item.value"
          :change="item.change"
          :icon="item.icon"
          :color="item.color"
        />
      </div>

      <!-- 悬浮按钮 -->
      <div class="scroll-buttons">
        <div
          class="scroll-button scroll-left"
          :class="{ disabled: !canScrollLeft, hidden: maxScroll <= 0 }"
          @click="canScrollLeft && scrollLeft()"
        >
          <el-icon><ArrowLeft /></el-icon>
        </div>

        <div
          class="scroll-button scroll-right"
          :class="{ disabled: !canScrollRight, hidden: maxScroll <= 0 }"
          @click="canScrollRight && scrollRight()"
        >
          <el-icon><ArrowRight /></el-icon>
        </div>
      </div>
    </div>

    <!-- 中部图表区域 -->
    <div class="chart-row">
      <div class="chart-container visitor-trend">
        <div class="chart-header">
          <h3>访客趋势</h3>
          <div class="chart-actions">
            <el-radio-group v-model="visitorTimeRange" size="small">
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
              <el-radio-button label="year">年</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <visitor-trend-chart :time-range="visitorTimeRange" />
      </div>

      <div class="chart-container geo-distribution">
        <div class="chart-header">
          <h3>访客地域分布</h3>
          <div>
            <el-radio-group v-model="geoViewType" size="small">
              <el-radio-button label="map">图表</el-radio-button>
              <el-radio-button label="list">列表</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div style="height: calc(100% - 50px)">
          <visitor-geo-chart :view-type="geoViewType" @view-change="(val) => (geoViewType = val)" />
        </div>
      </div>
    </div>

    <!-- 下部功能区域 -->
    <div class="feature-row">
      <div class="feature-container publish-heatmap" v-show="!isMobileView">
        <div class="feature-header">
          <h3>发布热力图</h3>
          <el-dropdown trigger="click">
            <el-button size="small">
              {{ yearOptions.find((y) => y.value === selectedYear)?.label || selectedYear + '年' }}
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="year in yearOptions"
                  :key="year.value"
                  @click="selectedYear = year.value"
                  >{{ year.label }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <publish-heatmap :year="selectedYear" />
      </div>

      <div class="feature-container hot-topics">
        <div class="feature-header">
          <h3>热门话题</h3>
          <el-button text type="primary" size="small">查看更多</el-button>
        </div>
        <hot-topics />
      </div>
    </div>

    <!-- 系统信息 -->
    <div class="system-info-wrapper" :class="{ collapsed: !hasActiveSystemInfo }">
      <SystemInfo @update:activeNames="handleSystemInfoCollapse" />
    </div>
  </div>
</template>

<script setup>
/**
 * 仪表盘页面
 *
 * 用于展示网站的关键数据和趋势，包括：
 * 1. 内容数据统计（文章、评论、相册、友链数）
 * 2. 访客统计和趋势分析
 * 3. 访客地域分布
 * 4. 内容发布热力图
 * 6. 热门话题概览
 */
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { Plus, ArrowDown, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import StatCard from './components/StatCard.vue'
import VisitorTrendChart from './components/VisitorTrendChart.vue'
import VisitorGeoChart from './components/VisitorGeoChart.vue'
import PublishHeatmap from './components/PublishHeatmap.vue'
import HotTopics from './components/HotTopics.vue'
import SystemInfo from './components/SystemInfo.vue'

/**
 * 统计卡片数据
 * 展示博客关键数据指标
 */
const statCards = [
  {
    id: 'articles',
    title: '文章数',
    value: 128,
    change: '+12%',
    icon: 'Document',
    color: 'primary',
  },
  {
    id: 'comments',
    title: '评论数',
    value: 3542,
    change: '+8.5%',
    icon: 'ChatDotRound',
    color: 'success',
  },
  {
    id: 'albums',
    title: '相册数',
    value: 24,
    change: '+4%',
    icon: 'Picture',
    color: 'warning',
  },
  {
    id: 'links',
    title: '友链数',
    value: 65,
    change: '+2%',
    icon: 'Link',
    color: 'info',
  },
  {
    id: 'visitors',
    title: '访客数',
    value: 15236,
    change: '+18.2%',
    icon: 'User',
    color: 'danger',
  },
]

/**
 * 访客趋势图时间范围控制
 */
const visitorTimeRange = ref('month')

/**
 * 地理分布视图类型
 */
const geoViewType = ref('map')

/**
 * 发布热力图年份控制
 */
const currentYear = new Date().getFullYear()
const selectedYear = ref(currentYear)
const yearOptions = [
  { label: `${currentYear}年`, value: currentYear },
  { label: `${currentYear - 1}年`, value: currentYear - 1 },
  { label: `${currentYear - 2}年`, value: currentYear - 2 },
  { label: `${currentYear - 3}年`, value: currentYear - 3 },
]

// 滚动控制
const statCardsRef = ref(null)
const scrollPosition = ref(0)
const maxScroll = ref(0)
const scrollStep = computed(() => {
  if (window.innerWidth <= 768) {
    // 移动端下滚动一个完整的卡片宽度（包含间距）
    return statCardsRef.value ? statCardsRef.value.clientWidth - 24 : 0
  }
  // PC端保持原有逻辑
  return statCardsRef.value ? statCardsRef.value.clientWidth / 4 : 0
})
let autoScrollInterval = null
const isHovering = ref(false)

// 计算最大滚动距离和滚动步长
const updateScrollMetrics = () => {
  if (statCardsRef.value) {
    const containerWidth = statCardsRef.value.clientWidth
    const scrollWidth = statCardsRef.value.scrollWidth
    const isMobile = window.innerWidth <= 768

    if (isMobile) {
      // 移动端下，考虑内边距和卡片间距
      maxScroll.value = scrollWidth - containerWidth
    } else {
      // PC端保持原有逻辑
      maxScroll.value = scrollWidth - containerWidth
    }
  }
}

// 左滚动
const scrollLeft = () => {
  if (statCardsRef.value) {
    const newPosition = Math.max(0, scrollPosition.value - scrollStep.value)
    scrollPosition.value = newPosition
    statCardsRef.value.scrollTo({
      left: newPosition,
      behavior: 'smooth',
    })
  }
}

// 右滚动
const scrollRight = () => {
  if (statCardsRef.value) {
    const newPosition = Math.min(maxScroll.value, scrollPosition.value + scrollStep.value)
    scrollPosition.value = newPosition
    statCardsRef.value.scrollTo({
      left: newPosition,
      behavior: 'smooth',
    })
  }
}

// 监听滚动事件
const handleScroll = () => {
  if (statCardsRef.value) {
    scrollPosition.value = statCardsRef.value.scrollLeft
    // 更新最大滚动距离，确保实时准确
    updateScrollMetrics()
  }
}

// 计算是否可以继续向右滚动
const canScrollRight = computed(() => {
  const isMobile = window.innerWidth <= 768
  if (isMobile) {
    // 移动端下，如果还有下一个卡片就可以滚动
    const currentCard = Math.round(scrollPosition.value / scrollStep.value)
    const totalCards = statCards.length
    return currentCard < totalCards - 1
  }
  // PC端保持原有逻辑
  return scrollPosition.value < maxScroll.value
})

// 计算是否可以向左滚动
const canScrollLeft = computed(() => {
  return scrollPosition.value > 0
})

// 自动滚动
const startAutoScroll = () => {
  if (!autoScrollInterval && !isHovering.value) {
    autoScrollInterval = setInterval(() => {
      if (!canScrollRight.value) {
        scrollPosition.value = 0
        statCardsRef.value?.scrollTo({
          left: 0,
          behavior: 'smooth',
        })
      } else {
        scrollRight()
      }
    }, 3000)
  }
}

const stopAutoScroll = () => {
  if (autoScrollInterval) {
    clearInterval(autoScrollInterval)
    autoScrollInterval = null
  }
}

// 鼠标进入停止自动滚动
const handleMouseEnter = () => {
  isHovering.value = true
  stopAutoScroll()
}

// 鼠标离开恢复自动滚动
const handleMouseLeave = () => {
  isHovering.value = false
  startAutoScroll()
}

// 移动端视图判断
const isMobileView = computed(() => {
  return window.innerWidth <= 768
})

// 监听窗口大小变化
const handleResize = () => {
  // 窗口大小变化时会自动触发 computed 重新计算
}

onMounted(() => {
  updateScrollMetrics()
  window.addEventListener('resize', updateScrollMetrics)
  window.addEventListener('resize', handleResize)
  if (statCardsRef.value) {
    statCardsRef.value.addEventListener('scroll', handleScroll)
  }
  startAutoScroll()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateScrollMetrics)
  window.removeEventListener('resize', handleResize)
  if (statCardsRef.value) {
    statCardsRef.value.removeEventListener('scroll', handleScroll)
  }
  stopAutoScroll()
})

const hasActiveSystemInfo = ref(false)

const handleSystemInfoCollapse = (activeNames) => {
  hasActiveSystemInfo.value = activeNames.length > 0
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 0 18px;
  height: 100%;
  overflow: auto;

  @media (max-width: 768px) {
    padding: 0;
  }

  // 顶部统计卡片布局
  .stat-cards-wrapper {
    position: relative;
    margin-bottom: 12px;
    padding: 8px 0;

    @media (max-width: 768px) {
      margin-bottom: 12px;
      padding: 8px 12px;
    }

    .stat-cards {
      display: flex;
      gap: 24px;
      overflow-x: auto;
      scroll-behavior: smooth;
      scrollbar-width: none;
      -ms-overflow-style: none;
      padding: 2px 0;
      width: 100%;
      scroll-snap-type: x mandatory;
      -webkit-overflow-scrolling: touch;

      @media (max-width: 768px) {
        gap: 0;
        padding: 0;
        scroll-snap-type: x mandatory;
        scroll-padding: 0;
      }

      &::-webkit-scrollbar {
        display: none;
      }

      > * {
        flex: 0 0 calc((100% - 72px) / 4);
        width: calc((100% - 72px) / 4);
        scroll-snap-align: start;
        scroll-snap-stop: always;

        @media (max-width: 768px) {
          flex: 0 0 100%;
          width: 100%;
          margin: 0;
          scroll-snap-align: center;
        }
      }
    }

    .scroll-buttons {
      position: absolute;
      top: 0;
      left: -8px;
      right: -8px;
      bottom: 0;
      pointer-events: none;

      @media (max-width: 768px) {
        display: none;
      }

      .scroll-button {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: var(--el-color-primary);
        color: white;
        cursor: pointer;
        pointer-events: auto;
        transition: all 0.3s ease;
        opacity: 0;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        z-index: 1;

        @media (max-width: 768px) {
          width: 28px;
          height: 28px;
          opacity: 0.9;

          .el-icon {
            font-size: 14px;
          }
        }

        &.scroll-left {
          left: 0;
        }

        &.scroll-right {
          right: 0;
        }

        &:hover:not(.disabled) {
          transform: translateY(-50%) scale(1.1);
          background: var(--el-color-primary-light-3);
        }

        &.disabled {
          background: var(--el-color-info-light-5);
          cursor: not-allowed;

          &:hover {
            transform: translateY(-50%);
          }
        }

        &.hidden {
          display: none;
        }

        .el-icon {
          font-size: 16px;
        }
      }
    }

    &:hover {
      .scroll-button {
        opacity: 0.9;

        &:hover:not(.disabled) {
          opacity: 1;
        }
      }
    }
  }

  // 系统信息行
  .system-info-wrapper {
    transition: all 0.3s ease;

    &.collapsed {
      margin: 20px 0; // 折叠时减少上下间距

      :deep(.el-collapse-item__header) {
        margin: 0; // 移除折叠时的边距
      }
    }

    @media (max-width: 768px) {
      padding: 0 12px;
    }
  }

  // 图表行布局
  .chart-row {
    display: grid;
    grid-template-columns: 3fr 2fr;
    gap: 16px;
    margin-bottom: 16px;

    @media (max-width: 1200px) {
      grid-template-columns: 1fr;
    }

    @media (max-width: 768px) {
      gap: 12px;
      margin-bottom: 12px;
      padding: 0 12px;
    }
  }

  // 功能行布局
  .feature-row {
    display: grid;
    grid-template-columns: 2.2fr 1fr;
    gap: 16px;
    margin-top: 16px;

    @media (max-width: 1400px) {
      grid-template-columns: 1fr;
    }

    @media (max-width: 768px) {
      gap: 12px;
      margin-top: 12px;
      padding: 0 12px;
    }
  }

  // 图表容器通用样式
  .chart-container,
  .feature-container {
    background-color: $bg-base;
    border-radius: $radius-medium;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
    min-height: 380px;

    @media (max-width: 768px) {
      min-height: 300px;
      padding: 12px;
      width: 100%;
      overflow: hidden;

      :deep(.echarts) {
        width: 100% !important;
        height: 100% !important;
      }
    }

    &.publish-heatmap {
      min-height: 420px;

      @media (max-width: 768px) {
        min-height: 340px;
      }
    }
  }

  // 图表头部通用样式
  .chart-header,
  .feature-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid $border-light;

    @media (max-width: 768px) {
      margin-bottom: 16px;
      padding-bottom: 12px;
    }

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: $text-primary;

      @media (max-width: 768px) {
        font-size: 15px;
      }
    }
  }

  // 访客趋势图高度
  .visitor-trend {
    height: 400px;

    @media (max-width: 768px) {
      height: 300px;
      width: 100%;
    }
  }

  // 地理分布图高度
  .geo-distribution {
    height: 400px;

    @media (max-width: 768px) {
      height: 300px;
      width: 100%;
    }
  }

  // 热力图高度
  .publish-heatmap {
    height: 420px;

    @media (max-width: 768px) {
      height: 340px;
      width: 100%;
    }
  }

  // 热门话题高度
  .hot-topics {
    height: 420px;

    @media (max-width: 768px) {
      height: 340px;
      width: 100%;
    }
  }

  // 系统信息
  .system-info {
    overflow: auto;

    :deep(.el-collapse) {
      --el-collapse-header-height: 42px;
    }
  }
}
</style>
